/**
 * Created by again on 2016/8/31.
 */
var businessKey='';
var processDefId = '';
var flowTypeArray=[];
$.ajaxSetup({cache:false});

// modal状态，来判断是否是二次打开，防止 hide.bs.modal，shown.bs.modal，show.bs.modal 被多次执行；

var firstStatus=true;
var processDetailStatus=true;
$('#myTabs').find('li').on('click',function () {
    processDetailStatus=true;
})
var myAuditHistoryResultArrived = null;

function successCheck(res) {
    var returnMessage = res.returnMessage
    if(res.returnCode == 0){

        $('#myDraft').modal('hide')
        tipModal('icon-checkmark',returnMessage,'',2e3);
        var processType=$("#processType").val();
        if(processType==null){
            processType="";
        }
        var activityIdSelect=$("#activityIdSelect").val();
        if(activityIdSelect==null){
            activityIdSelect="";
        }

        var startTime=$("#startTime").val();
        var endTime=$("#endTime").val();

        if("undefined" == typeof startTime){
            startTime="";
        }
        if("undefined" == typeof endTime){
            endTime="";
        }

        $.getJSON('/cwp/src/json/workflow/workflow_myTodoList.json',function(data){
            var processMyTodoTab = new LoaderTable("processWorkFlowTab","processWorkFlowTab","/cwp/front/sh/workflow!execute",
                "uid=myTodoList&processType="+processType+"&activityId="+activityIdSelect+"&startTime="+startTime+"&endTime="+endTime,Number($('#processWorkFlowTabPagination').find('.current').not('.prev').not('.next').html()),10,MyTodoListResultArrived,"");
            // processMyTodoTab.Display();
            processMyTodoTab.loadSuccessed(data);
        });
    }else{
        tipModal('icon-cross',returnMessage,'',2e3);
        $('#centerCheck').find('button').removeAttr('disabled');
    }

}

//当前工单号
var countOrderNum="";
var tempOptions="";
function graphTrace(options) {
    processDefId=options.processDefId
    tempOptions=options;
    if(!processDefId.match('MakeCard')){
        //维修工单详情
        myAuditHistoryResultArrived = function (result) {
            var bean=result.bean;
            $("#currentActivityName").text(bean.activityName);

            var baseInfo=$("#orderBaseInfo");
            var displayIds=["eventAddress","eventDescribe","planCompleteDate","actualCompleteDate","alarmNumber","serviceBudget","orderDescribe","serviceType"];
            $.each(displayIds,function(i,item){
                if(item=="serviceType"){
                    var text=bean[item]=="1"?"有偿服务":"无偿服务";

                    baseInfo.find("#"+item).text(text);
                    if(text=="无偿服务"){
                        $("#serviceBudgetCon").css("display","none");
                        $("#serviceTypeCon").addClass("width-all");
                    }else{
                        $("#serviceBudgetCon").removeAttr("style");
                        $("#serviceTypeCon").removeClass("width-all");
                    }
                }else if(item=="planCompleteDate"){
                    baseInfo.find("#"+item).text(bean[item].split(' ')[0]);
                }
                else if(item=="actualCompleteDate"){
                    if(bean["activityId"]=="endevent"){
                        baseInfo.find("#"+item).text(bean[item]);
                    }else{
                        baseInfo.find("#"+item).text("未完成");
                    }

                }else{
                    baseInfo.find("#"+item).text(bean[item]);
                }
            });



            var thead="<thead>"+
                "<tr>"+
                "<th>流程节点</th>"+
                "<th>审批时间</th>"+
                "<th>操作人员</th>"+
                "<th>操作</th>"+
                "<th>审批意见</th>"+
                "</tr>"+
                "</thead>";
            //拼接表格列表html
            var tbodys = "<tbody>";
            var beans=result.beans;

            for(var i=0;i<beans.length;i++){
                tbodys+="<tr><td>"+beans[i].activityName+"</td>"+
                    "<td>"+beans[i].operDate+"</td>"+
                    "<td>"+beans[i].person+"</td>"+
                    "<td>"+beans[i].operName+"</td>" +
                    "<td>"+beans[i].auditComment+"</td></tr>";
            }
            tbodys += "</tbody>";
            //显示表格html
            $("#myAuditHistoryTab").html(thead+tbodys);
        }
    }else {
        //一卡通工单详情
        myAuditHistoryResultArrived = function (res) {
            //申请信息
            $('#draftCurrentActivityName').text(res.bean.activityName);
            $('#DraftNumber').text(res.bean.orderNum);
            $('#applyTitle').text(res.bean.fileName);
            $('#DraftOrderDescribe').text(res.bean.orderDescribe);
            $('#DraftTime').text(res.bean.createTime);
            //申请部门
            $("#deptName").text(res.bean.deptName);
            $("#approver").text(res.beans[0].person);
            $("#phone1").text(res.bean.phone);
            $("#eidtApplyTitle").val(res.bean.fileName);
            $("#editDraftOrderDescribe").val(res.bean.orderDescribe);
            //获取开卡人信息列表
            countOrderNum=res.bean.orderNum;


            var userRole = userInfo.role[0].roleId;
            //获取所有开卡人列表
            if(res.bean.activityId=="applytask" && userRole=="52"){
                $("#editDraftOpt").show();
                $("#tabUser").show();
                $("#tabApprover").hide();
                $('#importantTip').show();
                getAllApprover();
            }else{
                $("#editDraftOpt").hide();
                $("#tabUser").hide();
                $("#tabApprover").show();
                $('#importantTip').hide();
                getApproverList(1);
            }

            var thead="<thead>"+
                "<tr>"+
                "<th>流程节点</th>"+
                "<th>审批时间</th>"+
                "<th>操作人员</th>"+
                "<th>操作</th>"+
                "<th>审批意见</th>"+
                "</tr>"+
                "</thead>";
            //拼接表格列表html
            var tbodys = "<tbody>";
            var beans=res.beans;

            for(var i=0;i<beans.length;i++){
                tbodys+="<tr><td>"+beans[i].activityName+"</td>"+
                    "<td>"+beans[i].operDate+"</td>"+
                    "<td>"+beans[i].person+"</td>"+
                    "<td>"+beans[i].operName+"</td>" +
                    "<td>"+beans[i].auditComment+"</td></tr>";
            }
            tbodys += "</tbody>";
            //显示表格html
            $("#myAuditHistoryTabDraft").html(thead+tbodys);
            $('#myDraft').modal('show');
            //提交审批
            $("#auditComment").on("keyup",function(){
                if($(this).val()){
                    $('#centerCheck').find('button').removeAttr('disabled');
                }else{
                    $('#centerCheck').find('button').attr('disabled','disabled');
                }
            });


        }
    }

    if(options.activityId == "AuditOrder") {
        return;
    }
    if(options.activityId == "AcceptanceOrder") {
        return;
    }
    if(options.activityId == "RepairFault") {
        return;
    }

        var userId=localStorage.getItem("parkId")
        if(userId==null||userId==undefined)
        {
            userId="";
        }
        businessKey=options.orderId;
        var _defaults = {
            srcEle: this,
            pid: $(this).attr('pid')
        };
        var opts = $.extend(true, _defaults, options);
        var host=window.location.protocol+"//"+window.location.host;

        initAuditHistoryList();

        // 获取图片资源
        var aid = opts.aid;
        var $modal = void 0;
        var isMakeCard =  opts.processDefId.split(":")[0] === 'MakeCard';
        isMakeCard ? $modal = $('#myDraft') : $modal = $("#modalProcessDetailsAlarm");
        $modal.data("businessKey",businessKey);
        var $img = $modal.find('img');


    //     PostForm("/cwp/front/sh/workflow!execute", "uid=traceProcess&businessKey=" + businessKey, "", function(infos) {
    //         var beanEntiy=jQuery.parseJSON(infos.object);
    // //
    //         if(true){
    //             $modal.modal({
    //                 keyboard : true,
    //                 backdrop : 'static'
    //             }).on('hidden.bs.modal',function(){
    //                 $('#workFlowTabs a:first').tab('show');
    //                 $img.removeAttr("src");
    // //                $("#modalProcessDetailsAlarm img").removeAttr("src");
    //                 processDetailStatus=false;
    //
    //             }).on('shown.bs.modal', function () {
    //
    //                 var orderId=$modal.data("businessKey");
    //                 var timestamp = Date.parse(new Date());
    //                 var imageUrl =host+"/cwp/front/sh/workflow!download?uid=readFlowResource&businessKey=" + orderId + "&resourceType=image&userId="+userId+"&_t="+timestamp;
    //
    //                 $img.attr('src', imageUrl).load(function () {
    // //                $("#modalProcessDetailsAlarm img").attr('src', imageUrl).load(function(){
    //                     // 执行一些动作...
    // //                    var width=$("#modalProcessDetailsAlarm img").width();
    //                     var width=$img.width();
    //
    // //                    var contentWidth=$("#modalProcessDetailsAlarm .flowContent").width();
    //                     var contentWidth = $modal.find(".flowContent").width();
    //                     var percent=contentWidth/width;
    //
    //                     $img.css({width:contentWidth});
    //
    //                     var positionHtml=bindHotPoint(beanEntiy,percent);
    // //                    $('#modalProcessDetailsAlarm #processImageBorder').html(positionHtml);
    //                     $modal.find('#processImageBorder').html(positionHtml)
    //                     $('.activity-attr').on('click', function() {
    //                     });
    //                     processDetailStatus=false;
    //                 });
    //             }).on('hide.bs.modal',function(){
    //             })
    //         }
    //         $modal.modal('show');
    //
    //     },"");

    $.getJSON('/cwp/src/json/workflow/workflow_traceProcess.json',function(infos){
        var beanEntiy=jQuery.parseJSON(infos.object);
        //
        if(true){
            $modal.modal({
                keyboard : true,
                backdrop : 'static'
            }).on('hidden.bs.modal',function(){
                $('#workFlowTabs a:first').tab('show');
                $img.removeAttr("src");
                //                $("#modalProcessDetailsAlarm img").removeAttr("src");
                processDetailStatus=false;

            }).on('shown.bs.modal', function () {

                var orderId=$modal.data("businessKey");
                var timestamp = Date.parse(new Date());
                // var imageUrl =host+"/cwp/front/sh/workflow!download?uid=readFlowResource&businessKey=" + orderId + "&resourceType=image&userId="+userId+"&_t="+timestamp;
                var imageUrl = "http://120.194.44.254:20888/cwp/front/sh/workflow!download?uid=readFlowResource&businessKey=20181128151709679650&resourceType=image&userId=b6b4d8e4-99b9-4485-87aa-83e381075c1b&_t=1543403726000";
                $img.attr('src', imageUrl).load(function () {
                    //                $("#modalProcessDetailsAlarm img").attr('src', imageUrl).load(function(){
                    // 执行一些动作...
                    //                    var width=$("#modalProcessDetailsAlarm img").width();
                    var width=$img.width();

                    //                    var contentWidth=$("#modalProcessDetailsAlarm .flowContent").width();
                    var contentWidth = $modal.find(".flowContent").width();
                    var percent=contentWidth/width;

                    $img.css({width:contentWidth});

                    var positionHtml=bindHotPoint(beanEntiy,percent);
                    //                    $('#modalProcessDetailsAlarm #processImageBorder').html(positionHtml);
                    $modal.find('#processImageBorder').html(positionHtml)
                    $('.activity-attr').on('click', function() {
                    });
                    processDetailStatus=false;
                });
            }).on('hide.bs.modal',function(){
            })
        }
        $modal.modal('show');

    })

}


//提交申请
var tempUid="";
var parameters="";
$('#centerCheck button').on('click',function () {

    var o = $.extend(
        {},
        tempOptions,
        {invalidOrder:$(this).attr("oper-id"),auditComment:$('#auditComment').val()});

    parameters=o;
    if(!o.auditComment){
        tipModal('icon-cross','请输入审批意见',"",1e3);
        return false;
    }

    var uid = void 0;
    switch(o.activityId){
        case "applytask":
            uid="m008";
            break;
        case "managertask" :
            uid = 'm002';
            break;
        case "leadertask" :
            uid = 'm003';
            break;
        case "maketask":
            uid = 'm004';
            $('#centerCheck').find('button').attr('disabled','disabled');
            break;
        default : break;
    }
    tempUid=uid;
    //获取用户选择审批人
    if($(this).attr("id")=="btnValid"){
        //起草工单重新编辑
        if(uid=="m008"){

            if($.formValidator.PageIsValid(3)){


                if(approverBeans.length==0){
                    tipModal('icon-cross',"请添加开卡人");

                }else{
                    var eidtApplyTitle=$("#eidtApplyTitle").val();
                    var editDraftOrderDescribe=$("#editDraftOrderDescribe").val();
                    var strApprover = JSON.stringify(approverBeans);
                    $("#hidEditCard").val(strApprover);
                    $("#hidEidtApplyTitle").val(eidtApplyTitle);
                    $("#hidEditDraftOrderDescribe").val(editDraftOrderDescribe);
                    showModalSelectApprover();
                }

            }


        }
        else if(uid=="m004"){
            // PostForm('/cwp/front/sh/makeCard!execute','uid='+uid+"&processInstId="+o.processInstId+"&taskId="+o.taskId+"&invalidOrder="+o.invalidOrder+"&businessKey="+o.businessKey,"",successCheck,"","frmOrderDes");
            $.getJSON('/cwp/src/json/workflow/makeCard_004.json',function(data){
                successCheck(data);
            });
        }
        else{
            showModalSelectApprover();
        }

    }
    else
    {
        $('#centerCheck').find('button').attr('disabled','disabled');
        // PostForm('/cwp/front/sh/makeCard!execute','uid='+uid+"&processInstId="+o.processInstId+"&taskId="+o.taskId+"&invalidOrder="+o.invalidOrder+"&businessKey="+o.businessKey,"",successCheck,"","frmOrderDes");
        $.getJSON('/cwp/src/json/workflow/makeCard_other.json',function(data){
            successCheck(data);
        });
    }
});


//确认审批人
$("#btnConfirmApprover").on("click",function(){
    if ($.formValidator.PageIsValid(2)) {
        $('#centerCheck').find('button').attr('disabled','disabled');
        var auditUserId=$("#auditUserId").val();
        $("#modalSelectApprover").modal("hide");
        PostForm('/cwp/front/sh/makeCard!execute','uid='+tempUid+"&auditUserId="+auditUserId+"&processInstId="+parameters.processInstId+"&taskId="+parameters.taskId+"&invalidOrder="+parameters.invalidOrder+"&businessKey="+parameters.businessKey,"",successCheck,"","frmOrderDes");

    }
});


$('#modalSelectApprover').on('hidden.bs.modal', function (e) {
   $("body").addClass("modal-open");
});

$('#modalCardholder').on('hidden.bs.modal', function (e) {
    $("body").addClass("modal-open");
});

$('#myTip').on('hidden.bs.modal', function (e) {
    $("body").addClass("modal-open");
});


//提交申请回调函数
function submitApply(result){
    if(result.returnCode=="0"){
        tipModal('icon-checkmark','提交成功');
        $("#hidEidtApplyTitle").val("");
        $("#hidEditDraftOrderDescribe").val("");
        $("#hidEditCard").val("");
        approverBeans=[];
    }
    else if(result.returnCode=="-9999"){
        tipModal('icon-cross',"提交失败");
    }
    else{
        tipModal('icon-cross',result.returnMessage);
    }
    $("#btnConfirmSubmit").removeAttr("disabled");
}



//请求申请人列表
function getApproverList(pageIndexs){
    var orderNum=countOrderNum;

    $.getJSON('/cwp/src/json/workflow/workflow_cu01.json',function(data){
        var loaderApproverList=new LoaderTableNew("tabApprover","/cwp/front/sh/cardUser!execute","uid=cu01&orderNum="+orderNum,pageIndexs,5,getApproverListResult,"",approverPagination);
        loaderApproverList.loadSuccessed(data);
        // loaderApproverList.Display();
        getApproverListResult(data);
    });
}


//申请人列表分页回调，加载容器1
var currentPage=0;
function approverPagination(page_index){
    currentPage=page_index;
    if(!isFirst) getApproverList(page_index+1);
}




function getApproverListResult(res){
    var thead="<thead>"+
        "<tr>"+
        "<th>姓名</th>"+
        "<th>性别</th>"+
        "<th>手机</th>"+
        "<th>员工编号</th>"+
        "<th>身份证号</th>"+
        "<th class='unBind'>一卡通卡号</th>"+
        "<th class='unBind'>操作</th>"+
        "</tr>"+
        "</thead>";
    var tbodys= "<tbody>";
    for(var i=0;i<res.beans.length;i++) {
        var user = res.beans[i];
        tbodys += "<tr>" +
            "<td>" + user.userName + "</td>" +
            "<td>" + (user.sex == "0" ? "男" : "女") + "</td>" +
            "<td>" + user.phone + "</td>" +
            "<td>" + user.standby + "</td>" +
            "<td>" + user.idCardNo + "</td>" +
            "<td class='unBind'>" + (user.cardNo==""?"无":user.cardNo) + "</td>" +
            "<td class='unBind'>" +
            (user.cardNo==""?"<a class='t-btn t-btn-blue btn-bind-card' data-id=" + user.id + "  data-phone=" + user.phone + "  data-trueName=" + user.userName + "    data-identityCard=" + user.idCardNo + ">绑卡</a>"
                :"<div class='t-btn' style='background: #E3E3E3;color: #777;'>绑卡</div>") +
            "</td>" +
            "</tr>"
    }
    tbodys+= "</tbody>";
    $("#tabApprover").html(thead+tbodys);
}


//-------------编辑起草一卡通开卡人列表
function getAllApprover(){
    //获取开卡人列表
    PostForm("/cwp/front/sh/cardUser!execute","uid=cu03&orderNum="+countOrderNum,"",getAllApproverResult,"");
}

var approverBeans = new Array();
function getAllApproverResult(result){
    approverBeans = result.beans;
    initPagination(approverBeans.length);
}

//excel导入



//初始化文件上传控件
$("#file_upload").uploadify({
    height        : 28,
    swf           : '../../assets/lib/uploadify/uploadify.swf',
    uploader      : '/cwp/front/sh/makeCard!execute?uid=m007',
    width         : 78,
    'fileTypeExts': '*.xls; *.xlsx', //文件后缀限制 默认：'*.*'
    'fileSizeLimit': '10240KB', //文件大小限制 0为无限制 默认KB
    'fileTypeDesc' : '.xls; *.xlsx文件格式',//文件类型描述
    'method': 'post', //提交方式Post 或Get 默认为Post
    'buttonText': '', //按钮文字
    'multi': false, //多文件上传
    'fileObjName': 'files[]', //设置一个名字，在服务器处理程序中根据该名字来取上传文件的数据。默认为Filedata
    'queueID': 'I am dont need',  //默认队列ID
    'removeCompleted': true, //上传成功后的文件，是否在队列中自动删除
    'overrideEvents': ['onDialogClose', 'onSelectError','onUploadStart', 'onUploadSuccess', 'onUploadError'],//重写事件
    //返回一个错误，选择文件的时候触发          
    'onSelectError': function (file, errorCode, errorMsg) {
        var msgText = "";
        switch (errorCode) {
            case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                //this.queueData.errorMsg = "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                msgText += "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                break;
            case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                msgText += "文件大小超过限制" + this.settings.fileSizeLimit + "";
                break;
            case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                msgText += "文件大小为0";
                break;
            case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                msgText += "文件格式不正确，仅限 " + this.settings.fileTypeExts;
                break;
            default:
                msgText += "错误代码：" + errorCode + "\n" + errorMsg;
        }
        tipModal('icon-cross',msgText);
    },
    // 当选中文件时的回调函数
    'onUploadStart': function (file) {
        //显示上传状态
        $("#uploadTip").text("正在上传...").attr("class","t-loading-cmcc");
    },

    //检测FLASH失败调用
    'onFallback': function () {
        alert("您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");
    },

    //文件上传成功后的回掉方法
    'onUploadSuccess': function (file, data, response) {
        var data=JSON.parse(data)
        if(data.returnCode == '0'){
            //excel列表数据
            approverBeans=data.beans;
            if(approverBeans.length>0){
                initPagination(approverBeans.length);
                tipModal('icon-checkmark','导入完成');
            }
        }
        else if(data.returnCode == '-9999'){
            tipModal('icon-cross','导入失败');
        }
        else{
            tipModal('icon-cross',data.result.returnMessage);
        }
        $("#uploadTip").text("批量导入").attr("class","t-btn t-btn-blue");
    },

    //文件上传出错时触发，参数由服务端程序返回。
    'onUploadError': function (file, errorCode, errorMsg, errorString) {
        tipModal('icon-cross',"上传出现异常，请重新上传");
    }
});


//当前页，加载容器
function paginationApprover(page_index){
    pageCount=page_index;
    searchUserList(page_index);
    return false;
}

var pageIndex=0;
var pageSize=5;
var pageCount=0;
//渲染导入申请人数据
function searchUserList(pageCount) {
    var data=approverBeans.slice(pageCount+pageCount*(pageSize-1),pageSize+pageCount*pageSize);
    if(data.length>0){
        $("#tabUserTip").hide();
        $("#tabUser").show();
        $("#tabApproverPagination").show();
        //获取搜索先关条件 默认搜索数据为空
        template.helper('genderFormat', function(inp) {
            if(inp == "0") {
                return '男';
            } else if(inp == "1") {
                return '女';
            }
        });
        var outHtml = template("approverListTmpl", data);
        $("#tabUser tbody").html(outHtml);

    }
    else{
        $("#tabUserTip").show();
        $("#tabUser").hide();
        $("#tabApproverPagination").hide();
    }


}


//分页
function initPagination(pageTotal){
    $("#tabApproverTotal").html("(共"+pageTotal+"条记录)");
    $("#tabApproverPagination").pagination(pageTotal, {
        num_edge_entries: 1, //边缘页数
        num_display_entries: 4, //主体页数
        callback: paginationApprover,
        items_per_page: pageSize, //每页显示1项
        current_page: pageIndex,
        prev_text: "上一页",
        next_text: "下一页",
        link_to:"javascript:void(0)"
    });
}


//---------------------------新增人员-----------------------------------
function showApproverModal(){
    $("#modalCardholder").modal({//启用modal ID
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal');
}

//添加开卡人
$("#btnAdd").on("click",function(){
    $("#modal-title-approver").text("新增开卡人员");
    $("#frmMainApprover input").val("");
    $("#frmMainApprover .tipArea div").html("").attr("class","");
    $("#boy").val("0");
    $("#girl").val("1");
    showApproverModal();

});

$(function(){
    formValidatorCard();
});

function formValidatorCard(){
    $.formValidator.initConfig({
        validatorGroup:"4",
        formid: "frmMainApprover", onerror: function (msg) {
            return false;
        }, onsuccess: function () {
            return true;
        }
    });

    $("#trueName").formValidator({
        validatorGroup:"4",
        onfocus: "请输入姓名",
        oncorrect: " "
    }).InputValidator({
        min: 4,
        max: 20,
        onempty: "请输入姓名",
        onerror: "姓名长度只能在4-8位字符之间"
    }).RegexValidator({
        regexp: "realname",
        datatype: "enum",
        onerror: "姓名只能为汉字"
    });

    $("#phone").formValidator({
        validatorGroup:"4",
        onfocus: "请输入手机号",
        oncorrect: " "
    }).InputValidator({
        min: 11,
        max: 11,
        onempty: "请输入手机号",
        onerror: "手机号码长度为11位"
    }).RegexValidator({
        regexp: "mobile",
        datatype: "enum",
        onerror: "手机号码格式无效"
    }).FunctionValidator({
        fun:function(val,elem) {
            var oldPhone = $("#oldPhone").val();
            if (oldPhone == val) {
                return true;
            }

            if (approverBeans.length > 0) {
                //本地数据验证
                for (var i = 0; i < approverBeans.length; i++) {
                    if (approverBeans[i].phone == val) {
                        return "该手机号码已添加";
                    }
                }
            }

            var htmlObj = $.ajax({
                type: "post",
                url: "/cwp/front/sh/makeCard!execute",
                beforeSend:function(requests){
                    requests.setRequestHeader("platform", "pc");
                },
                async: false,
                dataType: "json",
                data: {
                    uid: "m009",
                    userId: userId,
                    phone: $("#phone").val()
                }
            });
            var result = JSON.parse(htmlObj.responseText);
            if (result.returnCode == "0") {
                return true;
            } else {
                return "该手机号码已添加";
            }
        }
    });

    $("#emno").formValidator({
        validatorGroup:"4",
        onfocus: "请输入员工编号",
        oncorrect: " "
    }).InputValidator({
        min: 4,
        max: 20,
        onempty: "请输入员工编号",
        onerror: "员工编号长度为4-20个字符"
    }).FunctionValidator({
        fun:function(val,elem){
            var oldEmno=$("#oldEmno").val();
            if (val == oldEmno) {
                return true;
            }

            if(approverBeans.length>0){
                //本地数据验证
                for(var i=0; i<approverBeans.length; i++){
                    if(approverBeans[i].standby==val){
                        return "该员工编号已申请过";
                    }
                }
            }

            //数据库数据验证
            var htmlObj = $.ajax({
                type: "post",
                url: "/cwp/front/sh/makeCard!execute",
                beforeSend:function(requests){
                    requests.setRequestHeader("platform", "pc");
                },
                async: false,
                dataType: "json",
                data: {
                    uid: "m009",
                    userId: userId,
                    emno: $("#emno").val()
                }
            });
            var result = JSON.parse(htmlObj.responseText);
            if (result.returnCode == "0") {
                return true;
            } else {
                return "该员工编号已申请过";
            }
        }

    });


    $("#idno").formValidator({
        validatorGroup:"4",
        onshow:"请输入身份证号",
        onfocus:"请输入身份证号",
        oncorrect:"&nbsp;"
    }).InputValidator({
        min: 15,
        max: 18,
        onempty: "请输入身份证号",
        onerror: "身份证号的长度为15或18位"
    }).RegexValidator({
        regexp: "idcard",
        datatype: "enum",
        onerror: "请输入正确格式的身份证号"
    }).FunctionValidator({
        fun:function(val,elem){
            var oldIdno=$("#oldIdno").val();
            //数据库数据验证
            if (val == oldIdno) {
                return true;
            }
            else{
                var htmlObj = $.ajax({
                    type: "post",
                    url: "/cwp/front/sh/makeCard!execute",
                    beforeSend:function(requests){
                        requests.setRequestHeader("platform", "pc");
                    },
                    async: false,
                    dataType: "json",
                    data: {
                        uid: "m009",
                        userId: userId,
                        idno: $("#idno").val()
                    }
                });
                var result = JSON.parse(htmlObj.responseText);
                if (result.returnCode == "0") {
                    return true;
                } else {
                    return result.returnMessage;
                }
            }

            if(approverBeans.length>0){
                for(var i=0; i<approverBeans.length; i++){
                    if(approverBeans[i].idCardNo==val){
                        return "该身份证号已添加";
                    }
                }
            }


        }
    });
}



//提交申请人
$("#btnSave").on("click",function(){
    if ($.formValidator.PageIsValid(4)){
        var index=$("#hidIndex").val();
        if(index==""){
            var obj=new initApprover();
            approverBeans.unshift(obj);
            initPagination(approverBeans.length);
        }else{
            approverBeans[index].userName=$("#trueName").val();
            approverBeans[index].sex=$("[name='sex']:checked").val();
            approverBeans[index].phone=$("#phone").val();
            approverBeans[index].standby=$("#emno").val();
            approverBeans[index].idCardNo=$("#idno").val();
            //获取当前页
            paginationApprover(pageCount);
        }
        $('#modalCardholder').modal('hide');
    }
});

//初始化申请人对象
function initApprover(){
    this.userName=$("#trueName").val();
    this.sex=$("input[name='sex']:checked").val();
    this.phone=$("#phone").val();
    this.standby=$("#emno").val();
    this.idCardNo=$("#idno").val();
    this.cardNo="";
    this.cardStatus="";
    this.delFlag="";
    this.id="";
    this.orderNum="";
    return this;
}

//删除申请人
$(document).on("click","#btnDelete",function(){
    var phone=$(this).attr("data-phone");
    for(var i=0; i<approverBeans.length; i++){
        if(approverBeans[i].phone==phone){
            approverBeans.splice(i,1);
            initPagination(approverBeans.length);
        }
    }
});

//编辑申请人
$(document).on("click","#btnEdit",function(){
    var phone=$(this).attr("data-phone");
    userId = $(this).attr("data-id");
    for(var i=0; i<approverBeans.length; i++){
        if(approverBeans[i].phone==phone){
            $("#modal-title-approver").text("编辑开卡人员");
            $("#trueName").val(approverBeans[i].userName);
            if(approverBeans[i].sex=="0"){
                $("#boy")[0].checked=true;
            }
            else{
                $("#girl")[0].checked=true;
            }
            $("#phone").val(approverBeans[i].phone);
            $("#emno").val(approverBeans[i].standby);
            $("#idno").val(approverBeans[i].idCardNo);
            //隐藏域保存旧电话、旧员工编号、旧身份证
            $("#oldPhone").val(approverBeans[i].phone);
            $("#oldEmno").val(approverBeans[i].standby);
            $("#oldIdno").val(approverBeans[i].idCardNo);
            $("#hidIndex").val(i);
            showApproverModal();
        }
    }
});





//________________________my_________________________
//重新编辑起草表单验证
function draftFromValidator(){
    $.formValidator.initConfig({
        validatorGroup:"3",
        formid: "frmDraft", onerror: function (msg) {return false;}, onsuccess: function () {return true;}
    });
    $("#eidtApplyTitle").formValidator({
        validatorGroup:"3",
        onfocus: "请输入申请标题",
        oncorrect: " "
    }).InputValidator({
        validatorGroup:"3",
        min: 2,
        max: 40,
        onempty: "请输入申请标题",
        onerror: "标题长度为2到40个字符"
    });

    $("#editDraftOrderDescribe").formValidator({
        validatorGroup:"3",
        onfocus: "请输入申请原因",
        oncorrect: " "
    }).InputValidator({
        min: 2,
        max: 400,
        onempty: "请输入申请原因",
        onerror: "请输入申请原因"
    });
}

//权限设置
var userInfo="";
$(document).on("click",".t-btn-deal",function(){
    //初始化开卡人列表
    isFirst=true;
    //判断是查看详情或审批
    userInfo=JSON.parse(localStorage.getItem("userInfo"));
    if($(this).hasClass("trace")){
        $("#approvalComments").hide();
        $("#centerCheck").hide();
        if(userInfo.role.length>0){
            for(var i=0; i<userInfo.role.length; i++){
                var userRole = userInfo.role[i].roleId;
                switch (userRole){
                    case 55://制卡员
                        $("#tabApprover").addClass("showBind");
                        $("#btnValid").show();
                        break;
                    case 52://部门综合管理员
                        draftFromValidator();
                        $("#btnValid").hide();
                        $(".draftEit").hide();
                        $("#btnEndOrder").hide();
                        $("#invalidDisplayNone").show();
                        $("#applyTitle").show();
                        $("#DraftOrderDescribe").show();
                        break;
                    case 53://部门经理
                        break;
                }
            }

        }
    }else{
        $("#approvalComments").show();
        $("#centerCheck").show();
        var deptId=userInfo.childen.deptId;
        var userRole =0;
        if(userInfo.role.length>0){
            for(var i=0; i<userInfo.role.length; i++){
                var userRole = userInfo.role[i].roleId;
                switch (userRole){
                    case 55://制卡员
                        $("#tabApprover").addClass("showBind");
                        $("#btnValid").show();
                        break;
                    case 52://部门综合管理员
                        draftFromValidator();
                        $("#btnValid").show();
                        $("#invalidDisplayNone").hide();
                        $(".draftEit").show();
                        $("#btnEndOrder").show();


                        $("#applyTitle").hide();
                        $("#DraftOrderDescribe").hide();
                        break;
                    case 53://部门经理
                    case 54://综合管理领导
                        $("#btnValid").show();
                        $("#invalidDisplayNone").show();
                        break;
                }
            }

        }
        getApproer(deptId,userRole);
    }
});

//获取审批人列表
function getApproer(deptId,roleId){
    if(roleId==54 || roleId==53){
        deptId="";
    }
    roleId++;
    // PostForm("/cwp/front/sh/makeCard!execute", "uid=m006&deptId="+deptId+"&roleId="+roleId, "", getApproverResult, '');
    $.getJSON('/cwp/src/json/workflow/makeCard_m006.json',function(data){
        getApproverResult(data);
    });
}

function getApproverResult(result){
    if(result.returnCode=="0"){
        var option="";
        var selected="";
        $("#auditUserId").html("<option value=''>请选择</option>");
        for(var i=0; i<result.beans.length; i++){
            option="<option value='"+result.beans[i].parkId+"'>"+result.beans[i].trueName+"</option>"
            $("#auditUserId").append(option);
        }
        $("#auditUserId")[0].selectedIndex=1;
    }
    else if(result.returnCode=="-9999"){
        tipModal('icon-cross',"获取审批人失败");
    }
    else{
        tipModal('icon-cross',result.returnMessage);
    }
}


function showModalSelectApprover(){
    frmValidatorApprover();
    $("#modalSelectApprover").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
}


function frmValidatorApprover(){
    $.formValidator.initConfig({
        validatorGroup:"2",
        formid: "frmMainConfirmApprover", onerror: function (msg) {return false;}, onsuccess: function () {return true;}
    });

    $("#auditUserId").formValidator({
        validatorGroup:"2",
        onfocus: "请选择审批人",
        oncorrect: " "
    }).InputValidator({
        min: 1,
        onempty: "请选择审批人",
        onerror: "请选择审批人"
    });
}

    //$(function(){
    //    frmValidatorApprover();
    //});

//显示绑定模态框
$(document).on("click",".btn-bind-card",function(){
    $("#hidId").val($(this).attr("data-id"));
    $("#hidPhone").val($(this).attr("data-phone"));
    $("#hidTrueName").val($(this).attr("data-trueName"));
    $("#hidIdentityCard").val($(this).attr("data-identityCard"));
    showModalBindCard();
});

//绑定一卡通模态框
function showModalBindCard(){
    $('#cardNo').val("");
    $("#cardNoTip").attr("class","").html("");
    $("#modalBindCard").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
    frmValidatorBindCard();
}

function frmValidatorBindCard(){
    $.formValidator.initConfig({
        validatorGroup:"3",
        formid: "frmMainConfirmApprover",
        onerror: function (msg) {return false;},
        onsuccess: function () {return true;}
    });


    $("#cardNo").formValidator({
        validatorGroup:"3",
        onshow:"请输入一卡通卡号",
        onfocus:"请输入一卡通卡号",
        oncorrect:"&nbsp;"
    }).InputValidator({
        min: 8,
        max: 20,
        onempty: "请输入一卡通卡号",
        onerror: "卡号的长度为8-20个字符"
    }).RegexValidator({
        regexp: "cardNo",
        datatype: "enum",
        onerror: "卡号由数字组成"
    });
}

//绑定卡号
$(document).on("click","#btnBindCard",function(){
    if ($.formValidator.PageIsValid(3)) {
        //调用一卡通接口
        PostForm("/cwp/front/sh/pay!execute", "uid=P021", "", getExtInterfaceResult, '',"frmBindCard");
        $("#modalBindCard").modal("hide");
        showLoading();
    }
});


//显示加载界面
function showLoading(){
    $("#modalBindCardLoading").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
}

//调用一卡通外部接口回调函数
function getExtInterfaceResult(result){
    if(result.returnCode=="0"){
        PostForm("/cwp/front/sh/cardUser!execute", "uid=cu02&cardStatus=1", "", bindCardResult, '',"frmBindCard");
    }
    else if(result.returnCode=="-9999"){
        $("#modalBindCardLoading").modal("hide");
        tipModal('icon-cross',"一卡通外部接口调用失败");
    }
    else{
        $("#modalBindCardLoading").modal("hide");
        tipModal('icon-cross',result.returnMessage);
    }
}


//绑卡回调函数
function bindCardResult(result){
    $("#modalBindCardLoading").modal("hide");
    if(result.returnCode=="0"){
        tipModal("icon-checkmark", "绑定成功");
        approverPagination(currentPage);
    }
    else if(result.returnCode=="-9999"){
        tipModal('icon-cross',"提交失败");
    }
    else{
        tipModal('icon-cross',result.returnMessage);
    }
}


function bindMyAuditList(){

    /*
     var myAuditHistoryTab = new LoaderTable("myAuditHistoryTab","myAuditHistoryTab","/cwp/front/sh/workflow!execute",
     "uid=auditHistory&businessKey="+businessKey,
     1,10,myAuditHistoryResultArrived,"");*/

}

function initAuditHistoryList(){

    $.getJSON('/cwp/src/json/workflow/workflow_auditHistory.json',function(data){
        var myAuditHistoryTab = new LoaderTable("myAuditHistoryTab","myAuditHistoryTab","/cwp/front/sh/workflow!execute",
            "uid=auditHistory&businessKey="+businessKey+'&processDefId='+processDefId,
            1,10,myAuditHistoryResultArrived,"");
        // myAuditHistoryTab.Display();
        myAuditHistoryTab.loadSuccessed(data);
    });

}

function bindHotPoint(beanEntiy,percent){
    var positionHtml = "";
    var paddingWidth=15+2+1;
    var topOffset=51;

    $.each(beanEntiy, function(i, v) {
        var $positionDiv = $('<div/>', {
            'activityId' : v.activityId,
            'class': 'activity-attr'
        }).css({
            position: 'absolute',
            left: (v.x - 1)*percent+paddingWidth,
            top: (v.y - 1)*percent+paddingWidth+topOffset,
            width: (v.width - 2)*percent,
            height: (v.height - 2)*percent,
            backgroundColor: 'black',
            opacity: 0,
            zIndex: $.fn.qtip.zindex - 1
        });
        // 节点边框
        var $border = $('<div/>', {
            'class': 'activity-attr-border'
        }).css({
            position: 'absolute',
            left: (v.x - 1)*percent+paddingWidth,
            top: (v.y - 1)*percent+paddingWidth+topOffset,
            width: (v.width - 4)*percent,
            height: (v.height - 3)*percent,
            zIndex: $.fn.qtip.zindex - 2
        });
        positionHtml += $positionDiv[0].outerHTML + $border[0].outerHTML;
    });
    return positionHtml;
}



/**
 * 获取事件详细信息
 */
var globleOptions={};

function detailSelectToTask(options,beforeShow,afterShow){
    var $modal = void 0;
    options.processDefId.match('MakeCard') ? $modal = $('#myDraftDetails'):$modal = $('#modalMaintenanceDetails');
    var opts={
        modal:$modal
    }

    jQuery.extend(globleOptions,opts,options);


    if(firstStatus){
        $modal.modal({
            keyboard: true,
            backdrop: 'static'
        }).on('show.bs.modal', function(){

            if(beforeShow!=undefined && typeof beforeShow == 'function'){
                beforeShow && beforeShow(globleOptions);
            }
            firstStatus=false;

        }).on('shown.bs.modal',function(){
            if(afterShow!=undefined && typeof afterShow == 'function'){
                afterShow && afterShow(globleOptions);
            }
            firstStatus=false;

        }).on('hide.bs.modal',function(){

        })
    }
    $modal.modal("show");
}

function detailTaskWarningEvent(warningEventId){
    PostForm("/cwp/front/sh/warningEvent!execute", "uid=c003_4&warningEventId="+warningEventId, "", detailTaskWarningById, '');
}

function detailTaskWarningById(result){
    $('#warningLevel').html();
    var state="";
    if(result.bean.eventProcessStatus=="1"){
        state="未处理"
    }else if(result.bean.eventProcessStatus=="2"){
        state="处理中"
    }else if(result.bean.eventProcessStatus=="3"){
        state="已处理"
    }
    $('#deviceType').html(result.bean.deviceName)
    $('#deviceState').html(state);
    $('#devicePostion').html(result.bean.buildingName);
    if(result.bean.handName.length==0){
        $('#handlePerson').html('暂未处理');
    }else{
        $('#handlePerson').html(result.bean.handName);
    }
    $('#warningDescribe').html(result.bean.eventDescribe);
    if(result.bean.handName.length!=0){
        $('#handle').html(result.bean.handName);
    }else{
        $('#handle').html("暂时未处理");
    }
    if(result.bean.handleTime.length!=0){
        $('#handleTime').html(result.bean.handleTime);
    }else{
        $('#handleTime').html("暂时未处理");
    }


}


/*
 * post提交数据
 * 发送地址，uid，action行为，成功回调函数，失败回调函数
 *@author cheqniuxu
 *@created 2016/05/31
 *通过字典表查询字典数据表告警类别
 * */
//function processTypeList(){
//    PostForm("/cwp/front/sh/workflow!execute", "uid=processTemplate", "", processTypeListResultArrived, '');
//}
//
//function processTypeListResultArrived(result) {
//    console.log(result);
//    var sel = $("#processType").change(function(){
//    	var processDefId= $(this).children('option:selected').val();
//        var processDefId="FaultRepair:3:160714171754976901311300";
//    	console.log(processDefId);
//    	if($(this).val()!="" && $(this).val()!=null){
//    		PostForm("/cwp/front/sh/workflow!execute", "uid=processNode&processDefId="+processDefId, "", function(ret){
//    			console.log(ret);
//    		    var optionActivit = $("<option>").text("请选择").val("");
//    	    	var activitiSel=$("#activityIdSelect").empty().append(optionActivit);
//    	    	var processNodes=ret.object.processNode;
//    	        for (var i = 0; i < processNodes.length; i++) {
//    	        	if(processNodes[i].activityType=="startEvent" || processNodes[i].activityType=="endEvent" || processNodes[i].activityType=="userTask"){
//        	        	optionActivit = $("<option>").text(processNodes[i].activityName).val(processNodes[i].activityId);
//        	            activitiSel.append(optionActivit);
//    	        	}
//
//    	        }
//
//    		}, '');
//    	}else{
//    	    var optionActivit = $("<option>").text("请选择").val("");
//    		$("#activityIdSelect").empty().append(optionActivit);
//    	}
//    });
//
//
//    var option = ""
//    sel.empty();
//    option = $("<option>").text("请选择").val("");
//    sel.append(option);
//    var processList=result.object.processList;
//
//
//    for (var i = 0; i < processList.length; i++) {
//            option = $("<option>").text(processList[i].processDefName+":"+processList[i].version).val(processList[i].processDefId);
//            sel.append(option);
//            localStorage.setItem(processList[i].processDefId,processList[i].processDefName+":"+processList[i].version);
//    }
//}

$(function(){
    activityIdSelect();
});


$("#myTabs li").on("click",function(){
    activityIdSelect();
});

function activityIdSelect(){
    // PostForm("/cwp/front/sh/workflow!execute", "uid=processNode&processDefId=FaultRepair:3:160714171754976901311300", "", function(ret){
    //     var optionActivit = $("<option>").text("请选择").val("");
    //     var activitiSel=$("#activityIdSelect").empty().append(optionActivit);
    //     var processNodes=ret.object.processNode;
    //     for (var i = 0; i < processNodes.length; i++) {
    //         if(processNodes[i].activityType=="startEvent" || processNodes[i].activityType=="endEvent" || processNodes[i].activityType=="userTask"){
    //             optionActivit = $("<option>").text(processNodes[i].activityName).val(processNodes[i].activityId);
    //             activitiSel.append(optionActivit);
    //         }
    //     }
    //
    // }, '');
    $.getJSON('/cwp/src/json/workflow/workflow_processNode.json',function(ret){
        var optionActivit = $("<option>").text("请选择").val("");
        var activitiSel=$("#activityIdSelect").empty().append(optionActivit);
        var processNodes=ret.object.processNode;
        for (var i = 0; i < processNodes.length; i++) {
            if(processNodes[i].activityType=="startEvent" || processNodes[i].activityType=="endEvent" || processNodes[i].activityType=="userTask"){
                optionActivit = $("<option>").text(processNodes[i].activityName).val(processNodes[i].activityId);
                activitiSel.append(optionActivit);
            }
        }
    })
}
